package br.leiam.eolica.BD;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import br.leiam.eolica.excecoes.EolicaException;

public class Conexao {

	private static Conexao instance = null;
	private static Connection connection = null;

	private static String DATABASE_URL = "jdbc:mysql://localhost:3306/eolica";
	private static String USERNAME = "eolica";
	private static String PASSWORD = "eolica";

	public synchronized static Connection getConexao() throws EolicaException {
		if (instance == null) {
			instance = new Conexao();
		}
		return connection;
	}

	private Conexao() throws EolicaException {
		conectar();
	}

	synchronized static void conectar() throws EolicaException {
		try {
			if (connection == null || connection.isClosed()) {

				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection(DATABASE_URL,
						USERNAME, PASSWORD);

			}
		} catch (Exception e) {
			throw new EolicaException(e.getMessage());
		}
		// testConnection();
	}

	private static boolean testConnection() throws Exception {

		boolean output = false;
		try {
			Connection conexao = connection;
			Statement stmt = conexao.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);

			ResultSet srs = stmt
					.executeQuery("select datahora,direcao from roteiro where datahora between timestamp('2008-07-31 23:45:00') and timestamp('2008-07-31 23:50:00')");
			srs.afterLast();

			while (srs.previous() && !output) {
				String row_id = srs.getString("datahora");
				String login = srs.getString("direcao");
				output = true;
				System.out.println(row_id + " " + login);
			}
			System.out.println("Conectou!");
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connection.close();
			return output;
		}
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		connection.close();
	}

	// public static void main(String[] args) throws Exception {
	// Conexao.getConexao();
	// }
}
